<template>
  <div class="business">
    <div
      class="subDetail"
      v-for="item in formData.collections"
      :key="(item.subCode as string)"
    >
      <div class="head">
        <div class="sub-title">
          <p class="icon"></p>
          {{ item.cnName }}
        </div>
      </div>
      <div style="width: 90%; margin: auto">
        <a-form autoLabelWidth>
          <a-row :gutter="16">
            <a-col
              v-for="(ele, index) in item?.subRelDetail"
              :key="index"
              :span="(ele?.subsetControlRel?.span as number)"
            >
              <a-form-item :label="ele.ctlCnName" show-colon>
                <a-input
                  class="cn-input"
                  v-model="ele.ctlValue"
                  disabled
                  placeholder="自动获取"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <div>
          <!-- <a-row :gutter="16">
            <a-col
              v-for="(ele, index) in item.subRelDetail"
              :key="index"
              :span="(ele?.subsetControlRel.span as number)"
            >
              <a-space style="margin-bottom: 10px">
                <span>{{ ele.ctlCnName + ':' }}</span>
                <a-input style="width: 100%;" class="cn-input" disabled placeholder="自动获取" />
              </a-space>
            </a-col>
          </a-row> -->
          <!-- <div class="cn">
            <div
              class="cn-main"
              v-for="ele in item?.subRelDetail"
              :key="ele.ctlCode"
            >
              <span>{{ ele.ctlCnName + ':' }}</span>
              <a-input class="cn-input" disabled placeholder="自动获取" />
            </div>
          </div> -->
        </div>
      </div>
    </div>

    <div class="subDetail">
      <div class="head">
        <div class="sub-title">
          <p class="icon"></p>
          离职原因
        </div>
      </div>
      <div style="width: 90%; margin: auto">
        <div>
          <div>公司原因</div>
          <a-textarea
            v-model="formData.companyReasons"
            style="height: 150px; margin-top: 10px"
            placeholder="请填写公司原因"
            allow-clear
          />
        </div>
        <div style="margin-top: 20px">
          <div>个人原因</div>
          <a-textarea
            v-model="formData.peopleReasons"
            style="height: 150px; margin-top: 10px"
            placeholder="请填写个人原因"
            allow-clear
          />
        </div>
      </div>
    </div>
    <div class="subDetail">
      <div class="head">
        <div class="sub-title">
          <p class="icon"></p>
          面谈问题记录
        </div>
        <div @click="visibleProblem = true" class="setting">
          <icon-bookmark style="margin-right: 5px" />引用离职问题库
        </div>
      </div>
      <div style="width: 90%; margin: auto">
        <a-table
          :scroll="{
            x: 200,
            y: 200
          }"
          :pagination="false"
          :bordered="TableBorder"
          :columns="columns"
          :data="formData.talks"
          stripe
        >
          <template #rowIndex="{ rowIndex }"> {{ rowIndex + 1 }} </template>
          <template #operation="{ record, rowIndex }">
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer'
                }"
                @click="goEdit(rowIndex, record.id)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm
                content="是否确认删除该条数据?(注意：不用最后按保存也会直接删除该条数据！)"
                @ok="remove(rowIndex, record.id)"
              >
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </template>
        </a-table>
        <div
          @click="
            visible = true;
            currRecordIndex = -1;
          "
          style="padding: 20px; color: #3d7eff; cursor: pointer"
        >
          <icon-plus /> 新增问题
        </div>
      </div>
    </div>
    <div class="subDetail">
      <div class="head">
        <div class="sub-title">
          <p class="icon"></p>
          挽留可能性与措施
        </div>
      </div>
      <div style="width: 90%; margin: auto">
        <div class="main">
          <div class="left">
            <div>挽留可能性</div>
            <div style="height: 100px; line-height: 100px">建议挽留措施</div>
          </div>
          <div class="right">
            <div>
              <a-radio-group v-model="formData.possible">
                <a-radio :value="1">非常大</a-radio>
                <a-radio :value="2">较大</a-radio>
                <a-radio :value="3">一般</a-radio>
                <a-radio :value="4">较小</a-radio>
                <a-radio :value="5">很小</a-radio>
              </a-radio-group>
            </div>
            <a-textarea
              style="height: 100px"
              v-model="formData.advise"
            ></a-textarea>
          </div>
        </div>
      </div>
    </div>
    <div class="subDetail">
      <div class="head">
        <div class="sub-title">
          <p class="icon"></p>
          员工对公司的建议
        </div>
      </div>
      <div style="width: 90%; margin: auto">
        <a-textarea
          v-model="formData.peopleAdvise"
          style="height: 150px; margin-top: 20px"
          placeholder="Please enter something"
          allow-clear
        />
      </div>
    </div>
    <div class="subDetail">
      <div class="head">
        <div class="sub-title">
          <p class="icon"></p>
          面谈总结
        </div>
      </div>
      <div style="width: 90%; margin: auto">
        <a-textarea
          v-model="formData.summarize"
          style="height: 150px; margin-top: 20px"
          placeholder="Please enter something"
          allow-clear
        />
      </div>
    </div>
  </div>
  <a-modal
    title="新增问题"
    v-model:visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form :model="form">
      <a-form-item
        field="problem"
        label="问题"
        validate-trigger="input"
        required
      >
        <a-input v-model="form.problem" placeholder="请输入" />
      </a-form-item>
      <a-form-item field="reply" label="答复" validate-trigger="input">
        <a-textarea
          disabled
          v-model="form.reply"
          placeholder="请输入"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- <a-drawer
    title="离职问题库"
    :width="500"
    :visible="visibleProblem"
    @ok="problemOk"
    @cancel="visibleProblem = false"
    unmountOnClose
  >
    <a-tabs lazy-load v-model="key" @change="tabChange($event as number)">
      <a-tab-pane :key="1" title="审核中问题集">
        <div>
          <a-input-search
            :style="{ width: '320px' }"
            placeholder="请输入离职问题"
            search-button
            v-model="searchVal"
            @search="onSearch"
            @press-enter="onSearch"
          >
            <template #button-icon>
              <icon-search />
            </template>
          </a-input-search>
        </div>
        <TableTurn
          ref="tableRef1"
          :tableData="getData1"
          style="margin-top: 20px"
          :args="args"
        >
          <a-table-column :width="80">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column
            :width="200"
            title="离职问题"
            data-index="problem"
          ></a-table-column>
        </TableTurn>
      </a-tab-pane>
      <a-tab-pane :key="2" title="审核后问题集">
        <div>
          <a-input-search
            :style="{ width: '320px' }"
            placeholder="请输入离职问题"
            search-button
            v-model="searchVal"
            @search="onSearch"
            @press-enter="onSearch"
          >
            <template #button-icon>
              <icon-search />
            </template>
          </a-input-search>
        </div>
        <TableTurn
          ref="tableRef2"
          :tableData="getData2"
          style="margin-top: 20px"
          :args="args"
        >
          <a-table-column :width="80">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column
            :width="200"
            title="离职问题"
            data-index="problem"
          ></a-table-column>
        </TableTurn>
      </a-tab-pane>
    </a-tabs>
  </a-drawer> -->
</template>
<script setup lang="ts">
import { flatTree, dataTreeFilter } from '@/utils/utils';
import { GetPosition } from '@/apis/management/organization/positionManagement';
import { GetPositionLevelList } from '@/apis/management/organization/baseSetting';
import { GetHumanRosterDetail } from '@/apis/management/human/humanRoster';
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement';
import {
  DelLeaveInterViewListDetailProblem,
  PutLeaveInterViewListDetailProblem
} from '@/apis/management/human/humanChange/leave';
import { Message } from '@arco-design/web-vue';
import clonedeep from 'lodash.clonedeep';
const props = withDefaults(
  // 参数说明
  defineProps<{
    data?: any;
    problemData?: any; // 表格数据
  }>(),
  { problemData: () => [] }
);

let show = ref(false);
let formData = ref<any>({
  // collections: [], // 储存控件
  // companyReasons: '', // 公司原因
  // peopleReasons: '', // 个人原因
  // talks: [], // 面谈问题记录
  // possible: 1, // 挽留可能性 1非常大 2较大 3一般 4较小 5很小
  // advise: '', // 建议挽留措施
  // peopleAdvise: '', // 员工对公司的建议
  // summarize: '' // 面谈总结,
});

let positionLevelList = ref([]); // 职位层级数据
let organizationList = ref([]); // 组织数据
let positionList = ref([]);
const getSwitchData = async () => {
  try {
    const [organizationListRes, positionLevelListRes, positionListRes] =
      await Promise.all([
        // 获取部门类型
        GetOrganizationList({}),
        // 获取职位层级数据
        GetPositionLevelList({
          pageNumber: 0,
          pageSize: -1
        }),
        // 职位数据
        GetPosition({
          pageNumber: 0,
          pageSize: -1
        })
      ]);
    organizationList.value = flatTree(organizationListRes);
    positionLevelList.value = positionLevelListRes.content;
    positionList.value = positionListRes.content;
  } catch (error: unknown) {
    console.log(error);
  }
};

let userData = ref(), // 被面谈人信息
  responsibleData = ref(); // 面谈负责人信息

const needSwitchCode = [
  'CED44AC9966904CD1AB546D309903727C', // 部门
  'CA8ABCC1480744557B3014C3454465A7E', // 部门
  'C7341027925C943708F3AEF98703ECC47' // 职位
];
const getPeopleDetail = async () => {
  try {
    const [userDataRes, responsibleDataRes] = await Promise.all([
      GetHumanRosterDetail({
        id: formData.value.userId
      }),
      GetHumanRosterDetail({
        id: formData.value.responsibleId
      })
    ]);
    userDataRes.useTemplate.collectionModel.forEach((item1: any) => {
      item1.controlModel.forEach((item2: any) => {
        loop3: for (
          let i = 0;
          i < formData.value.collections[0]?.subRelDetail.length;
          i++
        ) {
          if (
            item2.ctlCode ===
            formData.value.collections[0]?.subRelDetail[i].ctlCode
          ) {
            if (needSwitchCode.includes(item2.ctlCode)) {
              formData.value.collections[0].subRelDetail[i].ctlValue =
                changeValue(item2.ctlValue.ctlValue, item2.ctlCode);
            } else
              formData.value.collections[0].subRelDetail[i].ctlValue =
                item2.ctlValue.ctlValue;
            break loop3;
          }
        }
      });
    });

    responsibleDataRes.useTemplate.collectionModel.forEach((item1: any) => {
      item1.controlModel.forEach((item2: any) => {
        loop3: for (
          let i = 0;
          i < formData.value.collections[1]?.subRelDetail.length;
          i++
        ) {
          if (
            item2.ctlCode ===
            formData.value.collections[1]?.subRelDetail[i].ctlCode
          ) {
            if (needSwitchCode.includes(item2.ctlCode)) {
              formData.value.collections[1].subRelDetail[i].ctlValue =
                changeValue(item2.ctlValue.ctlValue, item2.ctlCode);
            } else
              formData.value.collections[1].subRelDetail[i].ctlValue =
                item2.ctlValue.ctlValue;
            break loop3;
          }
        }
      });
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

// 转换数据
const changeValue = (id: string, ctlCode: string) => {
  const organizationData = organizationList.value.find(
    (item: any) => item.id == id
  );

  const positionListData = positionList.value.find(
    (item: any) => item.id == id
  );
  switch (ctlCode) {
    // 公司
    case 'CA8ABCC1480744557B3014C3454465A7E':
      return organizationData?.name;
    // 部门
    case 'CED44AC9966904CD1AB546D309903727C':
      return organizationData?.name;
    case 'C7341027925C943708F3AEF98703ECC47':
      return positionListData?.name;
    default:
      break;
  }
};

watch(
  () => props.data,
  async (newVal: any) => {
    formData.value = newVal;
    await getSwitchData();
    await getPeopleDetail();
  },
  {
    immediate: true
  }
);

const visible = ref(false);
const visibleProblem = ref(false);
const form = reactive({
  index: 0,
  // id: 0,
  problem: '',
  reply: ''
});
const key = ref(1);
let tableRef1 = ref(); // 储存表格的ref
let tableRef2 = ref(); // 储存表格的ref
const TableBorder = {
  wrapper: true,
  cell: true,
  headerCell: true,
  bodyCell: true
};
// 表格配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});
const columns: any = [
  {
    title: '序号',
    dataIndex: 'index',
    align: 'center',
    slotName: 'rowIndex'
  },
  {
    title: '问题',
    dataIndex: 'problem',
    align: 'center'
  },
  {
    title: '答复',
    dataIndex: 'reply',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    slotName: 'operation'
  }
];

let currRecordIndex = 0;
const remove = async (index: number, id: number) => {
  try {
    if (id) {
      await DelLeaveInterViewListDetailProblem({ id });
      formData.value.talks.splice(index, 1);
    } else formData.value.talks.splice(index, 1);
  } catch (error: unknown) {
    console.log(error);
  }
};
const goEdit = (index: number, id?: number) => {
  currRecordIndex = index;
  form.problem = formData.value.talks[index].problem;
  visible.value = true;
};
const problemOk = () => {
  const data: any = [];
  if (tableRef1.value.selectedListData.length) {
    tableRef1.value.selectedListData.forEach((ele: any) => {
      data.push({ problem: ele.problem, reply: '' });
    });
  }
  if (tableRef2.value.selectedListData.length) {
    tableRef2.value.selectedListData.forEach((ele: any) => {
      data.push({ problem: ele.problem, reply: '' });
    });
  }
  visibleProblem.value = false;
};
const handleOk = async () => {
  try {
    console.log(formData.value.talks);

    if (currRecordIndex === -1) {
      formData.value.talks.push({
        hid: formData.value.id ? formData.value.id : 0,
        problem: form.problem,
        reply: form.reply
      });
    } else {
      formData.value.talks[currRecordIndex].problem = form.problem;
      formData.value.talks[currRecordIndex].reply = form.reply;
    }
    if (formData.value.talks[currRecordIndex].id) {
      await PutLeaveInterViewListDetailProblem({
        ...formData.value.talks[currRecordIndex]
      });
    }
    visible.value = false;
    form.problem = '';
    form.reply = '';
  } catch (error: unknown) {
    console.log(error);
  }
};

const handleCancel = () => {
  form.problem = '';
  form.reply = '';
  visible.value = false;
};

defineExpose({
  formData
});
</script>
<style lang="less" scoped>
.business {
  width: 90%;
  // height: 100%;
  // overflow: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: auto;
  margin-bottom: 20px;
  .subDetail {
    width: 100%;
    .head {
      box-sizing: border-box;
      border-radius: 4px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      padding: 10px;
      background-color: #e8f0ff;
      margin: 20px 0;
      .sub-title {
        display: flex;
        align-items: center;
        .icon {
          border-radius: 4px;
          width: 6px;
          height: 70%;
          background-color: #3d7eff;
          height: 20px;
          padding: 0;
          margin: 3px 0;
          margin-right: 10px;
        }
      }
      .setting {
        color: #3d7eff;
        cursor: pointer;
      }
    }
  }
}
:deep(.arco-table-pagination) {
  display: none;
}
.main {
  display: flex;

  .left {
    flex: 1;
    div {
      text-align: center;
      line-height: 50px;
      width: 100%;
      height: 50px;
      border: 1px solid #e4e4e4;
    }
  }
  .right {
    flex: 4;
    div {
      padding-left: 20px;
      line-height: 50px;
      // width: 100%;
      height: 50px;
      border: 1px solid #e4e4e4;
    }
  }
}
</style>
